<template>
  <div class="upload-image-unit">
    <el-progress
      v-if="isUploading"
      type="circle"
      :percentage="uploadedPercentage"
      :status="uploadedPercentage == 100 ? 'success' : undefined"
      :width="178"
    ></el-progress>

    <el-upload
      v-else
      class="avatar-uploader"
      action="#"
      :show-file-list="false"
      :http-request="handleUploadImage"
    >
      <img v-if="value" :src="value" class="avatar" />
      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>
  </div>
</template>
<script>
import { uploadImage } from '@/api/course'

export default {
  name: 'UploadImageUnit',
  props: {
    value: { type: [String] }
  },
  data () {
    return {
      // 上传进度
      uploadedPercentage: 0,
      // 是否上传中
      isUploading: false
    }
  },
  methods: {
    // 上传
    handleUploadImage (option) {
      const fd = new FormData()
      fd.append('file', option.file)
      this.isUploading = true
      uploadImage(fd, (e) => {
        this.uploadedPercentage = Math.floor((e.loaded / e.total) * 100)
      })
        .then((res) => {
          if (res.data.code === '000000') {
            // 上传成功触发事件 实现双向绑定
            this.$emit('input', res.data.data.name)
          } else {
            this.$message.error('上传图片失败')
          }
        })
        .finally(() => {
          this.isUploading = false
        })
    }
  }
}
</script>
<style scoped lang="scss">
.avatar-uploader ::v-deep .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader ::v-deep .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
